package moe.cnkirito.security.oauth2.config;

import io.swagger.models.auth.In;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.OAuthBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.lang.reflect.Field;
import java.util.*;

//import static com.google.common.collect.Lists.newArrayList;


/**
  * swagger配置
  * 
  * @Author seven
  * @Date 9:17 19/12/10
*/
@Configuration
//@EnableSwagger2
@EnableOpenApi
public class Swagger2  implements WebMvcConfigurer {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.OAS_30)
                // 定义是否开启swagger，false为关闭，可以通过变量控制
                .enable(true)
                // 将api的元信息设置为包含在json ResourceListing响应中。
                .apiInfo(apiInfo())
                // 接口调试地址
                .host("http://localhost:8080") //http://localhost:${server.port}
                .select()
                .apis(RequestHandlerSelectors.any()) // RequestHandlerSelectors.basePackage("moe.cnkirito.security.oauth2"))
                .paths(PathSelectors.any())
                .build()
                // 支持的通讯协议集合
//                .protocols(newHashSet("https", "http"))
                // 授权信息设置，必要的header token等认证信息
                .securitySchemes(securitySchemes())
                // 授权信息全局应用
                .securityContexts(securityContexts());
    }

    //通过 securitySchemes 来配置全局参数，这里的配置是一个名为 Authorization 的请求头（OAuth2 中需要携带的请求头）
//    private List<ApiKey> securitySchemes() {
//        return newArrayList(
//                new ApiKey("Authorization","Authorization","header"));
//    }

    private static final String AUTH_SERVER = "http://localhost:8080";
    /**
     * 设置授权信息
     */
    private List<SecurityScheme> securitySchemes() {
//        ApiKey apiKey = new ApiKey("Authorization", "Authorization", In.HEADER.toValue());
//        return Collections.singletonList(apiKey);

//        //这个类决定了你使用哪种认证方式，我这里使用密码模式
//        GrantType grantType = new ResourceOwnerPasswordCredentialsGrant(AUTH_SERVER + "/oauth/token");
//        AuthorizationScope[] scopes = new AuthorizationScope[]{
//                new AuthorizationScope("all", "All scope is trusted!")
//        };
//        return Collections.singletonList(new OAuthBuilder()
//                .name("spring_oauth")
//                .grantTypes(Collections.singletonList(grantType))
//                .scopes(Arrays.asList(scopes))
//                .build());


        ApiKey apiKey = new ApiKey("BASE_TOKEN", "token", In.HEADER.toValue());
        return Collections.singletonList(apiKey);
    }



    //securityContexts 则用来配置有哪些请求需要携带 Token，这里我们配置了所有请求。
    private List<SecurityContext> securityContexts() {
//        return newArrayList(
//                SecurityContext.builder()
//                        .securityReferences(defaultAuth())
//                        .forPaths(PathSelectors.any())
//                        .build()
//        );

//        return Collections.singletonList(
//                SecurityContext.builder()
//                        .securityReferences(Collections.singletonList(new SecurityReference("Authorization", new AuthorizationScope[]{new AuthorizationScope("global", "")})))
//                        .build()
//        );


//        AuthorizationScope[] scopes = new AuthorizationScope[]{
//                new AuthorizationScope("all", "All scope is trusted!")
//        };
//        return Collections.singletonList(
//                SecurityContext.builder()
//                        .securityReferences(Collections.singletonList(new SecurityReference("spring_oauth", scopes)))
//                        .forPaths(PathSelectors.any())
//                        .build()
//        );

        return Collections.singletonList(
                SecurityContext.builder()
                        .securityReferences(Collections.singletonList(new SecurityReference("BASE_TOKEN", new AuthorizationScope[]{new AuthorizationScope("global", "")})))
                        .build()
        );
    }



//    List<SecurityReference> defaultAuth() {
//        AuthorizationScope authorizationScope = new AuthorizationScope("global","accessEverything");
//        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
//        authorizationScopes[0] = authorizationScope;
//        return newArrayList(
//                new SecurityReference("Authorization",authorizationScopes));
//    }
    private ApiInfo apiInfo() {//API 页面上半部分展示信息
        return new ApiInfoBuilder()
                .title("测试项目API")
                .description("描述")
                .contact(new Contact("联系人",null,"bob@126.com"))
                .termsOfServiceUrl("")
                .version("1.0")
                .build();
    }
    @SafeVarargs
    private final <T> Set<T> newHashSet(T... ts) {
        if (ts.length > 0) {
            return new LinkedHashSet<>(Arrays.asList(ts));
        }
        return null;
    }

    /**
     * 通用拦截器排除swagger设置，所有拦截器都会自动加swagger相关的资源排除信息
     */
    @SuppressWarnings("unchecked")
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        try {
            Field registrationsField = FieldUtils.getField(InterceptorRegistry.class, "registrations", true);
            List<InterceptorRegistration> registrations = (List<InterceptorRegistration>) ReflectionUtils.getField(registrationsField, registry);
            if (registrations != null) {
                for (InterceptorRegistration interceptorRegistration : registrations) {
                    interceptorRegistration
                            .excludePathPatterns("/swagger**/**")
                            .excludePathPatterns("/webjars/**")
                            .excludePathPatterns("/v2/**")
                            .excludePathPatterns("/doc.html");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
